package com.system.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.system.util.Tools;

public class CoreFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		String origin = req.getHeader("Origin");
		
		//带cookie的时候，origin必须是全匹配，不能用*
		if (Tools.notEmpty(origin)) {
			resp.addHeader("Access-Control-Allow-Origin", origin);
		}
		resp.addHeader("Access-Control-Allow-Methods", "*");
		
		//支持所有自定义头
		String headers = req.getHeader("Access-Control-Allow-Headers");
		if(Tools.notEmpty(headers)){
			resp.addHeader("Access-Control-Allow-Headers", headers);
		}
		resp.addHeader("Access-Control-Max-Age", "3600");
		
		//允许cookie
		resp.addHeader("Access-Control-Allow-Credentials", "true");
		chain.doFilter(req, resp);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
